﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for ShoppingCartAccess
/// </summary>
public class AccessGioHang
{
    public AccessGioHang()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static string idGioHang
    {
        get
        {
            // get the current HttpContext
            HttpContext context = HttpContext.Current;
            // try to retrieve the cart ID from the user session object
            string cartId = "";
            object cartIdSession = context.Session["TGDD_idGioHang"];
            if (cartIdSession != null)
                cartId = cartIdSession.ToString();
            // if the ID exists in the current session...
            if (cartId != "")
                // return its value
                return cartId;
            else
            // if the cart ID isn't in the session...
            {
                // check if the cart ID exists as a cookie
                if (context.Request.Cookies["TGDD_idGioHang"] != null)
                {
                    // if the cart exists as a cookie, use the cookie to get its value
                    cartId = context.Request.Cookies["TGDD_idGioHang"].Value;
                    // save the id to the session, to avoid reading the cookie next time
                    context.Session["TGDD_idGioHang"] = cartId;
                    // return the id
                    return cartId;
                }
                else
                // if the cart ID doesn't exist in the cookie as well, generate a new ID
                {
                    // generate a new GUID
                    cartId = Guid.NewGuid().ToString();
                    // create the cookie object and set its value
                    HttpCookie cookie = new HttpCookie(
                        "TGDD_idGioHang", cartId.ToString());
                    // set the cookie's expiration date 
                    int howManyDays = TGDDConfiguration.CartPersistDays;
                    DateTime currentDate = DateTime.Now;
                    TimeSpan timeSpan = new TimeSpan(howManyDays, 0, 0, 0);
                    DateTime expirationDate = currentDate.Add(timeSpan);
                    cookie.Expires = expirationDate;
                    // set the cookie on the client's browser
                    context.Response.Cookies.Add(cookie);
                    // save the ID to the Session as well
                    context.Session["TGDD_idGioHang"] = cartId;
                    // return the CartID
                    return cartId;
                }
            }
        }
    }
}
